package com.woyowodaows.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.lzy.okgo.OkGo;
import com.woyowodaows.R;
import com.woyowodaows.dialog.ProgressBarDialog;
import com.woyowodaows.request.HttpAsyncTask;
import com.woyowodaows.utils.DisplayUtils;
import com.woyowodaows.weight.LoadingDataLayout;


import java.lang.ref.WeakReference;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;


/**
 * @author haiwei
 *         所有activity可以继承此类 公共activity
 *         2017/2/22
 */
public abstract class BaseActivity extends SwipeBackActivity {

    protected RelativeLayout rlTitle;
    protected ImageView iv_get_back;
    protected TextView tvTitle;
    protected TextView tvRightText;
    public static LoadingDataLayout rlLayout;
    public Context mContext;
    protected View layoutView;
    protected int titleHeight;
    protected Bundle savedInstanceState;
    private AlertDialog networkLostToneDialog;//网络提示框
    private View view_line;
    public ProgressBarDialog progressBarDialog;
    protected int pageSize = 10;
    protected int pageNumber = 0;
    protected int maxPage = 1;
    protected boolean isRefresh = true;
    protected int totalNum = 1;

    protected void handleMessages(Message msg) {
    }

    public class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        public MyHandler(Activity activity) {
            mActivityReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            handleMessages(msg);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;
        setContentView(R.layout.activity_base);
        initView();
        initData();
        initEvent();
    }



    public  void initView() {
        //设置屏幕一直保持竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //当系统小于5.0则不支持右滑动退出
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            getSwipeBackLayout().setEdgeTrackingEnabled(SwipeBackLayout.STATE_IDLE);
        }
        mContext = BaseActivity.this;
        rlLayout = (LoadingDataLayout) findViewById(R.id.rl_layout);
        RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams
                (RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutView = View.inflate(mContext, getLayoutId(), null);
        layoutView.setLayoutParams(rp);
        rlLayout.addView(layoutView);
    }


    /**
     * 返回界面布局
     */
    public abstract int getLayoutId();

    /**
     * 初始化控件数据
     */
    public void initData() {
    }

    /**
     * 设置监听
     */
    public void initEvent() {
          rlLayout.setOnReloadListener(new LoadingDataLayout.OnReloadListener() {
              @Override
              public void onReload(View v, int status) {
                  onReloadData();
              }
          });
    }

    //重新加载数据
    private void onReloadData() {

    }

    public void hideTitle(){
      rlTitle = (RelativeLayout) findViewById(R.id.rl_title);
      rlTitle.setVisibility(View.GONE);
      setView_line(false);
    }

    /**
     * 设置标题栏
     *
     * @param isHideTitleBar       是否隐藏标题栏
     * @param titleText            中间文本
     * @param rightText            右边文本
     * @param leftDrawable         左边图片
     * @param rightDrawable        右边图片
     * @param rightOnClickListener 右边点击监听
     */
    protected void setTitleBar(boolean isHideTitleBar, String titleText, String rightText,
                               int leftDrawable, int rightDrawable, View.OnClickListener rightOnClickListener) {
        rlTitle = (RelativeLayout) findViewById(R.id.rl_title);
        if (isHideTitleBar) {
            setView_line(false);
            rlTitle.setVisibility(View.GONE);
        } else {
            if (titleText != null) {
                tvTitle = (TextView) findViewById(R.id.tv_title);
                tvTitle.setText(titleText);
            }
            iv_get_back = (ImageView) findViewById(R.id.iv_get_back);
           if (leftDrawable != 0) {
                iv_get_back.setImageResource(leftDrawable);
            }

            if (rightDrawable != 0 || rightText != null) {
                tvRightText = (TextView) findViewById(R.id.tv_right_text);
            }
            if (rightText != null && rightDrawable != 0) {
                Drawable drawable = getResources().getDrawable(rightDrawable);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                tvRightText.setCompoundDrawables(drawable, null, null, null);//画在右边
                tvRightText.setCompoundDrawablePadding(10);
                tvRightText.setText(rightText);
            } else if (rightText != null) {
                tvRightText.setText(rightText);
            } else if (rightDrawable != 0 ) {

                Drawable img = getResources().getDrawable(rightDrawable);
                // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
                tvRightText.setCompoundDrawables(img, null, null, null); //设置左图标
//                tvRightText.setBackgroundResource(rightDrawable);

            }

            iv_get_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DisplayUtils.hideSoftKeyboard(v,mContext);
                    finish();
                }
            });
            if (rightOnClickListener != null) {
                tvRightText.setOnClickListener(rightOnClickListener);
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    /**
     * 设置标题栏背景
     *
     * @param BackgroundResource
     */
    public void setTitleBackground(int BackgroundResource) {
        if (BackgroundResource != 0) {
            rlTitle.setBackgroundResource(BackgroundResource);
        }
    }

    /**
     * 设置标题
     *
     * @param titles
     */
    public void setTitles(String titles) {
        if (titles != null) {
            tvTitle.setText(titles);
        }
    }

    /**
     * 设置右边文本字体颜色
     *
     * @param color
     */
    public void setTextRightColor(String color) {
        if (color != null) {
            tvRightText.setTextColor(Color.parseColor(color));
        }
    }

    public void setTextRightColor(int colorId) {
        tvRightText.setTextColor(getResources().getColor(colorId));
    }


    public void setTexRightSize(float size) {

        tvRightText.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);

    }

    /**
     * 设置标题栏颜色
     * @param colorId
     */
    public void setTextTitleColor(int colorId) {
        tvTitle.setTextColor(getResources().getColor(colorId));
    }


    /**
     * 设置右边图片
     * @param drawableId
     */
    public void setTitelRightDrawable(int drawableId){
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        tvTitle.setCompoundDrawables(null, null, drawable, null);//画在右边
        tvTitle.setCompoundDrawablePadding(3);
    }

    /**
     * 设置右边图片和文本
     *
     * @param rightText
     * @param rightDrawable
     */
    public void setTextRightBackground(String rightText, int rightDrawable) {
        if (rightText != null && rightDrawable != 0) {
            Drawable drawable = getResources().getDrawable(rightDrawable);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
            if (tvRightText == null) {
                tvRightText = (TextView) findViewById(R.id.tv_right_text);
            }
            tvRightText.setCompoundDrawables(drawable, null, null, null);//画在右边
            tvRightText.setCompoundDrawablePadding(3);
            if (rightText != null && !" ".equals(rightText)) {
                tvRightText.setText(rightText);
            }
        }
    }


    /**
     * 为fragment设置functions，具体实现子类来做
     */
    public void setFunctionsForFragment(
            Object data) {
    }


    /**
     * 获取标题栏高度
     */
    protected void getTitleHeight() {
        if (rlTitle == null){
            rlTitle = (RelativeLayout) findViewById(R.id.rl_title);
        }
        ViewTreeObserver title = rlTitle.getViewTreeObserver();//四个节点以上的大布局
        title.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                titleHeight = rlTitle.getMeasuredHeight();
                rlTitle.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消请求
        OkGo.getInstance().cancelTag(mContext);
        //清空提示框
        HttpAsyncTask.getInstance().progressBarDialog = null;
        rlLayout = null;
        DisplayUtils.closeTransparencyStatusBar(this);
        //如果提示框已经创建对象 及时释放 防止内存泄漏
        if (networkLostToneDialog != null){
            networkLostToneDialog.cancel();
            networkLostToneDialog = null;
        }
        progressBarDialog = null;
    }


    /**
     * 设置水平线的展示
     * @param isVisible
     */
    public void setView_line(boolean isVisible) {
        view_line = findViewById(R.id.view_line);
        if (isVisible){
            view_line.setVisibility(View.VISIBLE);
        }else {
            view_line.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏dialog
     */
    public void dismissProgressDialog() {
        if (progressBarDialog != null) {
            progressBarDialog.dismissDialog();
        }
    }

    /**
     * 显示dialog
     *
     * @param context
     * @param promptInfo
     */
    public void showProgressDialog(Context context, String promptInfo) {
            if (progressBarDialog == null) {
                progressBarDialog = new ProgressBarDialog(context, promptInfo);
            } else {
                progressBarDialog.setContentText(promptInfo);
            }
            progressBarDialog.showDialog();
    }




    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }


    public void startActivity(Class<?> cls,String value) {
        Intent intent = new Intent(this, cls);
        intent.putExtra("value",value);
        startActivity(intent);
    }
}
